<template>
  <div class="app-container app-container-next app-container-detail" ref="container">
    <el-card class="box-card site" shadow="false">
      <div slot="header" class="clearfix">
        <router-link :to="{name: 'price-reduce-list'}">
          <el-button plain icon="el-icon-back" size="small" :round="true">
            返回
          </el-button>
        </router-link>
      </div>
      <div class="steps">
        <el-steps :active="activeForm" align-center>
          <el-step title="创建活动"></el-step>
          <el-step title="活动页面设置"></el-step>
        </el-steps>
      </div>
      <el-row style="margin-top: 20px" v-if="activeForm === 1">
        <el-col :span="18">
          <el-form ref="priceReduceForm" :model="priceReduce" label-width="120px">
            <h4 class="rebate-label">基本信息</h4>
            <el-form-item label="活动名称" prop="name"
                          :rules="[{required: true, message: '活动名称不能为空', trigger: 'blur'}, {max: 25, message: '名称最多输入25个字符串', trigger: 'blur'}]">
              <el-input v-model="priceReduce.name" placeholder="请输入活动名称" style="width: 460px"/>
            </el-form-item>
            <el-form-item label="活动时间" class="hasWidth" prop="date"
                          :rules="[{required: true, message: '活动时间不能为空', trigger: 'blur'}]">
              <al-date-picker v-model="priceReduce.date" format="yyyy-MM-dd HH:mm:ss" size="small"></al-date-picker>
            </el-form-item>
            <el-form-item label="优惠类型" prop="type"
                          :rules="[{required: true, message: '优惠类型不能为空', trigger: 'blur'}]">
              <el-select v-model="priceReduce.type" style="width: 460px">
                <el-option label="满额减元" :value=1></el-option>
                <el-option label="满额打折" :value=2></el-option>
              </el-select>
            </el-form-item>
            <h4 class="rebate-label">优惠规则</h4>

            <div class="marketing-row">
              <template v-for="(item, index) in priceReduce.levelList">
                <div :key="index">
                  <h5>优惠方案 {{ index + 1 }} <i style="margin-left: 12px" class="el-icon-delete"
                                              @click="handleRemoveLevel(index)" v-if="index !== 0"></i></h5>
                  <div class="marketing-row-conditions">
                    <el-form-item class="item" :prop="'levelList.' + index + '.fullValue'"
                                  :rules="[{required: true, message: '内容不能为空', trigger: 'blur'}, {validator: validateMin, trigger: 'blur'}]">
                      <el-input v-model="item.fullValue" placeholder="请输入" style="with:100%">
                        <template slot="prepend">满</template>
                        <template slot="append">{{currencyType}}</template>
                      </el-input>
                    </el-form-item>
                    <el-form-item class="item" :prop="'levelList.' + index + '.lessValue'"
                                  :rules="[{required: true, message: '内容不能为空', trigger: 'blur'},  {validator: validateMax, trigger: 'blur'}]">
                      <el-input v-model="item.lessValue" placeholder="请输入" style="with:100%">
                        <template slot="prepend">减</template>
                        <template slot="append">{{ priceReduce.type === 1 ? currencyType : '%' }}</template>
                      </el-input>
                    </el-form-item>
                  </div>
                </div>
              </template>
              <div class="marketing-row-tooltip" v-if="priceReduce.type === 1">
                <el-tooltip class="item" effect="dark"
                            placement="top">
                  <i class="el-icon-question"></i>
                  <template slot="content">
                    <span>如果勾选“上不封顶”如满 200 减 5，则满 200 减 5、满 400 减 10、满 600 减 15，以此类推；<br>如果未勾选“上不封顶”且只配置一个层级，则满 200 减 5、满 400 减 5、满 600 减 5；<br>如果配置多个层级，则按照层级满减。</span>
                  </template>
                </el-tooltip>
                <el-checkbox v-model="priceReduce.autoLevel">上不封顶</el-checkbox>
              </div>
              <el-button type="infos" icon="el-icon-plus" class="add-btn" @click="addLevel"
                         v-if="priceReduce.levelList.length<6">添加层级
              </el-button>
            </div>

            <h4 style="margin-bottom: 20px;justify-content: flex-start">适用范围

              <el-radio-group v-model="priceReduce.allProduct" class="radio-item-group">
                <el-radio :label=1 class="marketing-btn" :class="{'li_checked': priceReduce.allProduct === 1}"
                          style="margin-left: 60px">
                  <p class="title">选择全部商品</p>
                  <p class="desc">系统将自动排除已参加其他满减活动的商品</p>
                  <div class="checked_div" v-if="priceReduce.allProduct === 1">
                    <div class="checked_eae"></div>
                    <i aria-label="图标: check" class="anticon anticon-check checked_true_aea1">
                      <svg viewBox="64 64 896 896" class="" data-icon="check" width="1em" height="1em"
                           fill="currentColor"
                           aria-hidden="true" focusable="false">
                        <path
                            d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 0 0-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"></path>
                      </svg>
                    </i></div>
                </el-radio>
                <el-radio :label=0 class="marketing-btn" :class="{'li_checked': priceReduce.allProduct === 0}">
                  <p class="title">选择部分商品</p>
                  <p class="desc" v-if="priceReduce.allProduct === 1">仅限部分商品或款式参与该满减活动</p>
                  <p class="desc" v-if="priceReduce.allProduct === 0">已选择 {{ reduceProductList.length }} 件商品</p>
                  <p class="add" @click="handleSelectProduct" v-if="priceReduce.allProduct === 0">
                    <i aria-label="图标: plus" class="anticon anticon-plus"
                       style="font-size: 14px; font-weight: 700; color: rgb(31, 125, 248); padding-right: 5px;">
                      <svg viewBox="64 64 896 896" class="" data-icon="plus" width="1em" height="1em"
                           fill="currentColor"
                           aria-hidden="true" focusable="false">
                        <path d="M482 152h60q8 0 8 8v704q0 8-8 8h-60q-8 0-8-8V160q0-8 8-8z"></path>
                        <path d="M176 474h672q8 0 8 8v60q0 8-8 8H176q-8 0-8-8v-60q0-8 8-8z"></path>
                      </svg>
                    </i>继续添加商品
                  </p>
                  <div class="checked_div" v-if="priceReduce.allProduct === 0">
                    <div class="checked_eae"></div>
                    <i aria-label="图标: check" class="anticon anticon-check checked_true_aea1">
                      <svg viewBox="64 64 896 896" class="" data-icon="check" width="1em" height="1em"
                           fill="currentColor"
                           aria-hidden="true" focusable="false">
                        <path
                            d="M912 190h-69.9c-9.8 0-19.1 4.5-25.1 12.2L404.7 724.5 207 474a32 32 0 0 0-25.1-12.2H112c-6.7 0-10.4 7.7-6.3 12.9l273.9 347c12.8 16.2 37.4 16.2 50.3 0l488.4-618.9c4.1-5.1.4-12.8-6.3-12.8z"></path>
                      </svg>
                    </i></div>
                </el-radio>
              </el-radio-group>
            </h4>
            <h4 style="margin-bottom: 20px;justify-content: flex-start">商品排序展示
              <el-form-item style="margin: 0;" prop="sort">
                <el-select v-model="priceReduce.sort" placeholder="请选择" style="width: 200px">
                  <el-option label="价格从低到高" value="price_low_to_high"/>
                  <el-option label="价格从高到低" value="price_high_to_low"/>
                  <el-option label="实际销量从高到低" value="sale_count_high_to_low"/>
                  <el-option label="虚拟销量从高到低" value="virtual_sale_count_high_to_low"/>
                </el-select>
              </el-form-item>
            </h4>
            <h4 style="margin-bottom: 20px" v-if="priceReduce.allProduct === 0">满减商品</h4>
            <el-table :data="reduceProductList" fit highlight-current-row v-if="priceReduce.allProduct === 0">
              <el-table-column align="center" label="商品图片">
                <template slot-scope="scope">
                  <el-image
                      slot="reference"
                      style="width: 80px; height: 60px;cursor: pointer;"
                      :src="scope.row.productImage"
                      fit="contain"></el-image>
                </template>
              </el-table-column>
              <el-table-column align="center" label="商品名称" prop="productName" :show-overflow-tooltip="true"/>
              <el-table-column align="center" label="款式" prop="productSpec" :show-overflow-tooltip="true"/>
              <el-table-column align="center" :label="'售价(' + currencyType + ')'" prop="sellPrice">
                <template slot-scope="{row}">
                  <p>{{ row.sellPrice| currency('$') }}</p>
                </template>
              </el-table-column>
              <el-table-column align="center" label="操作">
                <template slot-scope="scope">
                  <el-button size="mini" plain type="danger" @click="handleRemove(scope.$index, scope.row)">退出活动
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <el-form-item class="fixBottom">
              <el-button type="primary" @click="handleSubmit('priceReduceForm')" :loading="submitLoading">保存</el-button>
              <el-button @click="handleReset('priceReduceForm')">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row style="margin-top: 20px" v-if="activeForm === 2">
        <el-col :span="18">
          <el-form ref="priceReduce2Form" :model="priceReduce2" label-width="140px">
            <h4 style="margin-bottom: 20px">活动Banner
              <span class="desc">推荐尺寸：
                <span v-if="priceReduce2.displayMode==='full'">1920PX * 300PX</span>
                <span v-if="priceReduce2.displayMode!=='full'">1410PX * 300PX</span>
              </span>
            </h4>
            <el-form-item prop="imageUrl">
              <upload-file accept="image/jpeg,image/jpg,image/png"
                           :fileType="['png', 'jpg', 'jpeg']"
                           :isShowTip="true"
                           :lazy="true"
                           :responseFn="handleResponse"
                           :action="uploadPath"
                           title="图片"
                           v-model="priceReduce2.imageUrl"
              ></upload-file>
            </el-form-item>
            <el-form-item label="展示方式">
              <el-radio-group v-model="priceReduce2.displayMode">
                <el-radio label="full">铺满全屏</el-radio>
                <el-radio label="padding">两边留白</el-radio>
              </el-radio-group>
            </el-form-item>
            <h4>弹窗配置 <span class="desc">可在弹窗公告中查看详情</span> </h4>
            <el-form-item>
              <el-checkbox v-model="addActivityView">创建优惠弹窗</el-checkbox>
            </el-form-item>
            <h4>倒计时提醒文案 <span class="desc">该提醒文案将展示在活动页面 banner 下方</span></h4>
            <div class="preview"
                 :style="{background: `linear-gradient(90deg, ${priceReduce2.countdown.baseMap1}, ${priceReduce2.countdown.baseMap2})`, justifyContent: priceReduce2.showCount ? 'space-between' : 'center'}"
                 style="margin-bottom:20px;height: 82px">
              <div v-if="priceReduce2.showCount"><span class="flashsale_text" :style="{color: priceReduce2.countdown.copyColor}">FLASH SALE</span>
                <span style="margin-left: 12px; color: rgb(254, 255, 254);">
                  <span class="inline-block" style="margin-right: 10px;">End in </span>
                </span>
                <span v-if="priceReduce2.unit === '1'">
                  <span class="time"
                        :style="{color: priceReduce2.countdown.countdownCopyColor, background: priceReduce2.countdown.backgroundColor}">134</span>
                  <span style="margin: 0px 4px;color: #fff">Day</span></span>
                  <span class="time"
                        :style="{color: priceReduce2.countdown.countdownCopyColor, background: priceReduce2.countdown.backgroundColor}">23</span><span
                    style="color: rgb(254, 255, 254);"> : </span><span class="time"
                                                                       :style="{color: priceReduce2.countdown.countdownCopyColor, background: priceReduce2.countdown.backgroundColor}">26</span><span
                    style="color: rgb(254, 255, 254);"> : </span><span class="time"
                                                                       :style="{color: priceReduce2.countdown.countdownCopyColor, background: priceReduce2.countdown.backgroundColor}">52</span><span
                    style="color: rgb(254, 255, 254);"> : </span><span class="align-bottom time"
                                                                       :style="{color: priceReduce2.countdown.countdownCopyColor, background: priceReduce2.countdown.backgroundColor}"
                                                                       style="font-size: 20px;">187</span>
              </div>
              <div class="rules_list"
                   style="color: rgb(231, 6, 73); margin-right: 20px;" :style="{background: priceReduce2.countdown.tips_background_color}">
                <svg class="badge_left" width="16" height="42" xmlns="http://www.w3.org/2000/svg">
                  <path
                      d="M16 41H1.467c-.98 0-1.704-1.029-1.395-2.005l5.032-17.09c.103-.324.103-.65 0-.92L.072 3.005C-.237 1.975.486 1 1.467 1h10.965c.826 0 1.884.911 1.884 1.778v33.778c0 .888.22 1.733.842 3.555.143.419.423.715.842.889z"
                      :fill="priceReduce2.countdown.tips_background_color" fill-rule="evenodd"></path>
                </svg>
                <svg class="badge_right" width="17" height="42" xmlns="http://www.w3.org/2000/svg">
                  <path
                      d="M.317 41H14.85c.98 0 1.704-1.029 1.395-2.005l-5.031-17.09c-.104-.324-.104-.65 0-.92l5.03-17.98C16.555 1.975 15.832 1 14.85 1H3.885c-.826 0-1.884.911-1.884 1.778v33.778c0 .888-.22 1.733-.842 3.555A1.424 1.424 0 01.317 41z"
                      :fill="priceReduce2.countdown.tips_background_color" fill-rule="evenodd"></path>
                </svg>
                <div class="truncate max-w-lg"><span :style="{color: priceReduce2.countdown.tips_color}">Buy {{currency(1000, currencySymbol)}} more and save {{currency(100, currencySymbol)}}</span></div>
              </div>
            </div>
            <el-form-item label="是否显示倒计时">
              <el-switch v-model="priceReduce2.showCount"></el-switch>
            </el-form-item>
            <el-form-item label="活动倒计时显示单位">
              <el-radio-group v-model="priceReduce2.unit">
                <el-radio label="1">天-时-分-秒-毫秒</el-radio>
                <el-radio label="2">时-分-秒-毫秒</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item label="底色">
              <el-color-picker
                  v-model="priceReduce2.countdown.baseMap1"
                  :predefine="predefineColors">
              </el-color-picker>
              <el-color-picker
                  v-model="priceReduce2.countdown.baseMap2"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item label="文案颜色">
              <el-color-picker
                  v-model="priceReduce2.countdown.copyColor"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item label="倒计时背景颜色">
              <el-color-picker
                  v-model="priceReduce2.countdown.backgroundColor"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item label="倒计时文案颜色">
              <el-color-picker
                  v-model="priceReduce2.countdown.countdownCopyColor"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item label="提醒文案背景颜色">
              <el-color-picker
                  v-model="priceReduce2.countdown.tips_background_color"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item label="提醒文案文字颜色">
              <el-color-picker
                  v-model="priceReduce2.countdown.tips_color"
                  :predefine="predefineColors">
              </el-color-picker>
            </el-form-item>
            <el-form-item class="fixBottom">
              <el-button type="primary" @click="activeForm = 1">上一步</el-button>
              <el-button type="primary" @click="savePriceReduce('priceReduce2Form')">保存</el-button>
              <el-button @click="handleReset">取消</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
    </el-card>
    <el-dialog title="选择商品" :visible.sync="productDialogVisible" width="960px">
      <div class="search-list 111">
        <el-form ref="form" class="search-table-form"
                 :model="formParams" label-width="90px" size="small" style="background: #fff;padding: 10px">
          <el-row :gutter="20" style="margin: 0">
            <el-col :span="6">
              <el-form-item label="产品系列：">
                <el-select v-model="formParams.seriesId"  @change="handleSearch">
                  <el-option v-for="series in seriesList" :value="series.value"
                             :key="series.value" :label="series.label"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品类型：">
                <el-select v-model="formParams.spuType"  @change="handleSearch">
                  <el-option value="" label="全部商品"></el-option>
                  <el-option value="0" label="普通商品"></el-option>
                  <el-option value="1" label="定制商品"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="上架状态：">
                <el-select v-model="formParams.published"  @change="handleSearch">
                  <el-option value="" label="全部"></el-option>
                  <el-option :value="1" label="上架"></el-option>
                  <el-option :value="0" label="下架"></el-option>
                  <el-option :value="-1" label="未上架"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="商品名称：">
                <el-input v-model="formParams.text" placeholder="请输入" @keyup.enter.native="handleSearch" style="width: 100%"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="5" style="text-align: left">
              <p>
                已选择 {{ filterSelectData(productList).length }} 件商品
              </p>
            </el-col>
            <el-col :span="19" style="text-align: right">
              <el-form-item>
                <el-button size="small" type="primary" @click="handleSearch">搜索查询</el-button>
                <el-button size="small" type="default" @click="handleRest">重置</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <tree-table
          v-if="productDialogVisible"
          v-loading.lock="tableLoading"
          height="400px"
          tree-props="skuDTOList"
          id-key="skuId"
          :columns="columns"
          @select="onSelect"
          @trigger="onTrigger"
          :data="tableData"
          border
          ref="treeTable"
      >
        <template slot-scope="scope" slot="product">
          <el-image :src="scope.row.productImage" style="width: 40px;height: 40px;" fit="contain"></el-image>
          <span>{{ scope.row.productName }}</span>
        </template>
      </tree-table>
      <LoadMore v-if="tableData.length > 0 && !isMore" :is-more="isMore" @on-change="onLoad"></LoadMore>
      <span slot="footer" class="dialog-footer">
    <el-button @click="productDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="handleAddProduct">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import uploadFile from '_c/Upload/uploadFile';
import {getProductPage, addPriceReduce} from '@/api/priceReduce';
import {getSeriesList} from '@/api/goods';
import LoadMore from '_c/LoadMore/index';
import {currency, utcFormat} from '@/utils/filters';
import settings from '_c/theme-editor/config/subscriptionPopus';
import TreeTable from '_c/Tables/tree-table';
import {debounce, deepClone} from '@/utils/utils';
import {mapGetters} from 'vuex';

let seriesOptionList = [{value: '', label: '全部'}];
export default {
    name: 'price-reduce-add',
    components: {uploadFile, LoadMore, TreeTable},
    data () {
        return {
            currency,
            isMore: false,
            tableLoading: false,
            formParams: {
                page: 1,
                pageSize: 20,
                text: '',
                seriesId: '',
                spuType: '',
                published: ''
            },
            seriesList: [],
            addActivityView: false,
            fixOption: {fixedHeader: true},
            activeForm: 1,
            predefineColors: [
                '#ff4500',
                '#ff8c00',
                '#ffd700',
                '#90ee90',
                '#00ced1',
                '#1e90ff',
                '#c71585',
                'rgba(255, 69, 0, 0.68)',
                'rgb(255, 120, 0)',
                'hsv(51, 100, 98)',
                'hsva(120, 40, 94, 0.5)',
                'hsl(181, 100%, 37%)',
                'hsla(209, 100%, 56%, 0.73)'
            ],
            tableData: [],
            priceReduce2: {
                imageUrl: '',
                unit: '1',
                displayMode: 'full',
                popUpsSetting: '1',
                showCount: true,
                countdown: {
                    baseMap1: 'rgb(255, 72, 72)',
                    baseMap2: 'rgb(255, 13, 125)',
                    copyColor: 'rgb(254, 255, 254)',
                    backgroundColor: 'rgb(255, 243, 203)',
                    countdownCopyColor: 'rgb(0, 0, 0)',
                    tips_background_color: 'rgb(255, 248, 227)',
                    tips_color: 'rgb(231, 6, 73)'
                }
            },
            productList: [],
            reduceProductList: [],
            priceReduce: {
                name: '',
                date: [],
                startTime: '',
                endTime: '',
                sort: 'price_low_to_high',
                type: 1,
                allProduct: 0,
                autoLevel: false,
                levelJson: '',
                styleJson: '',
                productList: [],
                levelList: [{fullValue: '', lessValue: ''}]
            },
            uploadPath: process.env.VUE_APP_BASE_API + '/upload-file',
            rules: {
                name: [
                    {required: true, message: '请输入活动名称', trigger: 'blur'}
                ],
                date: [
                    {required: true, message: '请选择活动时间', trigger: 'blur'}
                ]
            },
            validateMin: (rule, value, callback) => {
                // let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d+)?$/;
                let reg = /^([1-9]{1}\d*)$/;
                let one = Number(value);
                const maxField = rule.field.split('.')[1];
                if (this.priceReduce.levelList[maxField - 1] && +this.priceReduce.levelList[maxField - 1].fullValue >= +this.priceReduce.levelList[maxField].fullValue) {
                    return callback(new Error('下级必须大于上级'));
                }

                let max = Number(this.priceReduce.levelList[maxField].lessValue);
                if (!reg.test(one)) {
                    return callback(new Error('只能输入大于零的整数'));
                } else if (this.priceReduce.type === 1 && one < max) {
                    return callback(new Error('优惠条件必须大于优惠金额'));
                }
                return callback();
            },
            validateMax: (rule, value, callback) => {
                // let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d+)?$/;
                let reg = /^([1-9]{1}\d*)$/;
                let one = Number(value);
                if (!reg.test(one)) {
                    return callback(new Error('只能输入大于零的整数'));
                }
                const minField = rule.field.split('.')[1];
                let min = Number(this.priceReduce.levelList[minField].fullValue);
                if (this.priceReduce.type === 1) {
                    if (one >= min) {
                        return callback(new Error('优惠金额必须小于优惠条件'));
                    }
                } else {
                    if (one < 1 || one > 99) {
                        return callback(new Error('只能输入 1-99 的整数'));
                    }
                }
                if (this.priceReduce.levelList[minField - 1] && +this.priceReduce.levelList[minField - 1].lessValue >= +this.priceReduce.levelList[minField].lessValue) {
                    return callback(new Error('下级必须大于上级'));
                }
                return callback();
            },
            submitLoading: false,
            pageParams: {
                page: 1,
                pageSize: 20
            },
            productDialogVisible: false,
            formOptions: {
                showResetBtn: true,
                showSearchBtn: true,
                inline: false,
                labelWidth: 120,
                submitBtnText: '查询',
                size: 'small',
                resetBtnCallback: () => {
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                },
                forms: [
                    {
                        prop: 'seriesId',
                        label: '产品系列：',
                        itemType: 'select',
                        placeholder: '请选择产品系列',
                        options: this.seriesOptionList,
                        selectChange: (e, params) => {
                            this.pageParams.seriesId = e;
                        }
                    },
                    {
                        prop: 'published',
                        label: '上架状态：',
                        itemType: 'select',
                        placeholder: '请选择上架状态',
                        options: [
                            {label: '上架', value: 1},
                            {label: '下架', value: 0},
                            {label: '未上架', value: -1}
                        ]
                    },
                    {prop: 'searchText', label: '商品名称：', placeholder: '请输入商品名称'}
                ]
            },
            columns: [
                {
                    label: '',
                    type: 'selection',
                    selectable (row, index) {
                        if (row.disable) {
                            return 0;
                        } else {
                            return 1;
                        }
                    }
                },
                {
                    label: '商品',
                    prop: 'productName',
                    showOverflowTooltip: true,
                    slotName: 'product',
                    align: 'center',
                    width: '300px'
                },
                {
                    label: '款式',
                    prop: 'skuValues',
                    align: 'center',
                    showOverflowTooltip: true
                },
                {
                    label: '价格',
                    render: row => {
                        if (row.sellPrice) {
                            return currency(row.sellPrice, '$', 2);
                        }
                        return '';
                    },
                    align: 'center'
                },
                {
                    label: '备注',
                    prop: 'description',
                    align: 'center'
                }
            ]
        };
    },
    watch: {
        'priceReduce.autoLevel' (newValue, oldValue) {
            if (newValue && this.priceReduce.levelList.length > 1) {
                this.$confirm('选择上不封顶，只有优惠层级 1 生效，其他都会失效，是否确认选择', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.priceReduce.levelList = this.priceReduce.levelList.slice(0, 1);
                }).catch(() => {
                    this.priceReduce.autoLevel = false;
                });
            }
        },
        'priceReduce.date' (newValue, oldValue) {
            if (newValue) {
                this.priceReduce.productList = [];
                this.productList = [];
                this.reduceProductList = [];
                // if (this.$refs.treeTable) {
                //     this.$refs.treeTable.setSelected(this.reduceProductList);
                // }
            }
        },
        activeForm (newValue, oldValue) {
            if (newValue) {
                this.$nextTick(() => {
                    this.$refs.container.scrollTo(0, 0);
                });
            }
        }
    },
    methods: {
        onLoad () {
            this.formParams.page++;
            this.getProductPage().then(() => {
                this.$refs.treeTable.setSelected(this.priceReduce.productList);
            });
        },
        getSeriesList () {
            getSeriesList({siteId: this.siteId}).then(res => {
                if (res.data !== undefined && res.data.length > 0) {
                    const seriesList = [];
                    seriesList.push({value: '', label: '全部'});
                    for (const object of res.data) {
                        seriesList.push({value: object.value, label: object.label});
                    }
                    this.seriesList = seriesList;
                }
            });
        },
        getProductPage (params = {}) {
            if (this.priceReduce.date === undefined || this.priceReduce.date == null || this.priceReduce.date.length !== 2) {
                this.$message.error('请选择活动时间');
                return false;
            }
            return new Promise(resolve => {
                params.siteId = this.siteId;
                params.beginDate = new Date(this.timestampToTime(this.priceReduce.date[0]) + ' UTC' + this.timeZone).getTime();
                params.endDate = new Date(this.timestampToTime(this.priceReduce.date[1]) + ' UTC' + this.timeZone).getTime();
                getProductPage({...this.formParams, ...params}).then(res => {
                    this.productList = [];
                    this.tableLoading = false;
                    this.total = res.totalElements;
                    if (res.records.length === 0) {
                        this.isMore = true;
                    }
                    if (res.records.length < this.pageSize) {
                        this.isMore = true;
                    }
                    if (this.formParams.page === 1) {
                        this.tableData = res.records;
                    } else {
                        this.tableData = this.tableData.concat(res.records);
                    }
                    resolve(this.tableData);
                }).catch(() => {
                    this.tableLoading = false;
                    this.productDialogVisible = false;
                });
            });
        },
        handleResponse (response, file, fileList) {
            return response;
        },
        nextStep (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.activeForm = 2;
                }
            });
        },
        handleSearch () {
            this.tableLoading = true;
            this.formParams.page = 1;
            this.getProductPage();
        },
        handleRest () {
            this.formParams = {
                page: 1,
                pageSize: 20,
                text: '',
                seriesId: '',
                spuType: '',
                published: ''
            };
            this.getProductPage();
        },
        handleReset () {
            this.$router.push({name: 'price-reduce-list'});
        },
        handleSelectProduct () {
            this.productList = [];
            this.reduceProductList = [];
            if (this.priceReduce.date.length === 2) {
                this.productDialogVisible = true;
                this.tableLoading = true;
                this.getProductPage();
            } else {
                this.$message.error('请选择活动时间');
            }
        },
        filterSelectData (data) {
            return data.filter(item => item.$level === 1);
        },
        handleAddProduct () {
            this.productDialogVisible = false;
            this.reduceProductList = this.filterSelectData(deepClone(this.productList));
        },
        handleRemove (index, record) {
            this.reduceProductList.splice(index, 1);
        },
        addLevel () {
            if (this.priceReduce.autoLevel) {
                this.$confirm('新增优惠层级，上不封顶功能将会失效。请确认是否新增', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.priceReduce.autoLevel = false;
                    this.priceReduce.levelList.push({fullValue: '', lessValue: ''});
                });
            } else {
                this.priceReduce.levelList.push({fullValue: '', lessValue: ''});
            }
        },
        handleSubmit (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    if (this.priceReduce.allProduct === 1) {
                        this.priceReduce.productList = [];
                        this.activeForm = 2;
                        return false;
                    }
                    if (this.priceReduce.allProduct !== 1 && this.reduceProductList.length <= 0) {
                        this.$message.error('请先设置满减商品');
                        return false;
                    }
                    if (this.reduceProductList && this.reduceProductList.length > 0) {
                        let tempList = [];
                        this.reduceProductList.forEach(item => {
                            tempList.push({'spuId': item.spuId, 'skuId': item.skuId});
                        });
                        this.priceReduce.productList = tempList;
                    }
                    this.activeForm = 2;
                }
            });
        },
        handleRemoveLevel (index) {
            this.priceReduce.levelList.splice(index, 1);
        },
        onSelect: debounce(function (selection) {
            this.productList = selection;
        }, 1200),
        onTrigger (row, expanded) {
            row.$expanded = expanded;
        },
        savePriceReduce (name) {
            let reduceDates = this.priceReduce.date;
            if (reduceDates === undefined || reduceDates == null || reduceDates.length !== 2) {
                this.$message.error('请先设置活动时间');
                return false;
            }
            if (this.priceReduce.levelList == null || this.priceReduce.levelList.length <= 0) {
                this.$message.error('请先设置活动优惠层级');
                return false;
            }
            this.$refs[name].validate(valid => {
                if (valid) {
                    this.priceReduce.siteId = this.siteId;
                    this.priceReduce.activityImage = this.priceReduce2.imageUrl;
                    let startTime = this.timestampToTime(this.priceReduce.date[0]);
                    let finishTime = this.timestampToTime(this.priceReduce.date[1]);
                    this.priceReduce.startTime = new Date(startTime + ' UTC' + this.timeZone).getTime();
                    this.priceReduce.endTime = new Date(finishTime + ' UTC' + this.timeZone).getTime();
                    let tempLevelList = [];
                    this.priceReduce.levelList.forEach(item => {
                        let tempLevel = {'fullValue': (parseFloat(item['fullValue']) * 100).toString()};
                        let lessValue = item['lessValue'];
                        if (this.priceReduce.type === 1) { // 满额减元
                            tempLevel['lessValue'] = (parseFloat(lessValue) * 100).toString();
                        } else {
                            tempLevel['lessValue'] = lessValue;
                        }
                        tempLevelList.push(tempLevel);
                    });
                    this.priceReduce.levelJson = JSON.stringify(tempLevelList);
                    // delete this.priceReduce.date;
                    // delete this.priceReduce2.imageUrl;
                    // delete this.priceReduce.levelList;
                    this.priceReduce.styleJson = JSON.stringify(this.priceReduce2);
                    if (this.addActivityView) {
                        this.priceReduce.showActivityView = 1;
                        this.priceReduce.viewJson = this.getReduceActivityTemplate();
                    } else {
                        this.priceReduce.showActivityView = 0;
                    }
                    addPriceReduce(this.priceReduce).then(res => {
                        this.$message.success('新增成功');
                        this.$router.push({name: 'price-reduce-list'});
                    });
                }
            });
        },
        getReduceActivityTemplate () {
            // 获取满减活动默认配置信息
            if (!settings || settings.length <= 0) {
                return '';
            }
            let templates = settings.filter(item => item.name === 'Subscription');
            if (!templates || templates.length <= 0) {
                return '';
            } else {
                return JSON.stringify(templates[0]['value']);
            }
        },
        timestampToTime (timestamp) {
            var date = new Date(timestamp);// 时间戳为10位需*1000，时间戳为13位的话不需乘1000
            var Y = date.getFullYear() + '-';
            var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
            var D = (date.getDate() < 10 ? '0' + date.getDate() : date.getDate()) + ' ';
            var h = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
            var m = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
            var s = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
            let strDate = Y + M + D + h + m + s;
            return strDate;
        }
    },
    computed: {
        ...mapGetters(['timeZone', 'siteList']),
        siteId () {
            return this.$store.state.user.siteId;
        },
        siteInfo () {
            let info = this.siteList.find(res => res.id === Number(this.siteId));
            return info;
        },
        currencyType () {
            return this.siteInfo.currencyType;
        },
        currencySymbol () {
            return this.siteInfo.currencySymbol;
        }
    },
    created () {
        this.getSeriesList();
    }
};
</script>

<style scoped lang="scss">
.app-container {
  overflow: scroll;
  height: 800px;
}
.steps {
  width: 40%;
  margin: 10px auto;
}

.rebate-label {
  margin-bottom: 20px !important;
}

.radio-item-group {
  display: flex;
  align-items: center;

  .radio-item {
    display: flex;
    align-items: center;

    .radio-item-input {
      margin-left: 10px;
    }
  }
}

.groups-conditions {
  display: flex;
  align-items: center;

  .item {
    margin-right: 20px;
    margin-bottom: 20px;
  }
}

.sorting-panel {
  .search {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;

    .inline-item {
      width: 200px;
    }
  }

  .list-wrap {
    > div {
      width: 100%;
      display: flex;
      align-items: center;
      flex-wrap: wrap;
    }

    .image-item {
      position: relative;
      margin-right: 10px;
      margin-bottom: 10px;
      border: 1px solid #c0ccda;
      border-radius: 6px;
      overflow: hidden;
      cursor: pointer;
      width: 200px;
      background-color: #f7f7f7;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 10px;

      .img {
        position: relative;
        height: 148px;

        img {
          width: 148px;
          height: 148px;
        }

        &:hover {
          .label {
            display: flex;
          }
        }
      }

      .title {
        height: 36px;
        margin: 5px 0;
        color: #30344f;
        font-size: 12px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        text-align: center;
        width: 100%;
      }

      .label {
        flex-direction: row;
        justify-content: center;
        align-items: center;
        width: 100%;
        height: 32px;
        text-align: center;
        position: absolute;
        bottom: 0;
        background-color: #000000;
        color: white;
        opacity: 0.6;
        display: none;
        line-height: 32px;
      }
    }
  }
}

.preview {
  margin: 20px 0 0 0;
  width: 100%;
  height: 48px;
  background: linear-gradient(135deg, #ff4848, #ff0d7d);
  padding: 0 100px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 16px;

  .flashsale_text {
    font-size: 16px;
    font-weight: 700;
  }

  .inline-block {
    display: inline-block;
  }

  .time {
    display: inline-block;
    padding: 0 4px;
    min-width: 35px;
    height: 26px;
    line-height: 26px;
    text-align: center;
    border-radius: 4px;
  }

  .rules_list {
    margin-right: 20px;
    position: relative;
    padding: 12px;
    height: 44px;
    display: flex;
    justify-content: center;
    align-items: center;
    color: #e70649;
    background: #fff8e3;
    font-size: 18px;
    border-radius: 4px;

    .badge_left {
      position: absolute;
      top: 3px;
      left: -16px;
    }

    .badge_right {
      position: absolute;
      top: 3px;
      right: -17px;
    }

    .truncate {
      overflow: hidden !important;
      text-overflow: ellipsis !important;
      white-space: nowrap !important;
    }
  }
}

.marketing-btn {
  cursor: pointer;
  border: #c5cddb 1px solid;
  border-radius: 4px;
  width: 200px;
  padding: 10px 32px;
  text-align: center;
  margin-right: 40px;
  white-space: unset;
  height: 120px;
  display: flex;
  flex-wrap: wrap;
  justify-content: center;

  &.li_checked {
    cursor: pointer;
    border: #1f7df8 2px solid;
    border-radius: 4px;
    width: 200px;
    padding: 10px 32px;
    text-align: center;
    margin-right: 40px;
    background: #f4f8ff;
    white-space: unset;
    height: 120px;
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
  }

  .title {
    color: #30354d;
    font-size: 14px;
  }

  .desc {
    font-size: 12px !important;
    line-height: 20px;
    color: #7e849c;
    font-weight: 400;
    margin: 0 !important;
  }

  .checked_div {
    position: absolute;
    right: 0;
    top: 0;
    height: 28px;
    width: 28px;

    .checked_eae {
      position: absolute;
      top: 0;
      right: 0;
      width: 0;
      height: 0;
      border-top: 28px solid #1f7df8;
      border-left: 28px solid transparent;
    }

    .checked_true_aea1 {
      color: #fff;
      font-size: 16px;
      font-weight: 700;
      position: absolute;
      top: 0;
      right: 0;
    }

    .anticon {
      transition: margin-left 0.3s cubic-bezier(0.645, 0.045, 0.355, 1);
    }
  }

}
</style>

<style lang="scss">
.radio-item-group {
  display: flex;
  align-items: center;

  .radio-item {
    display: flex;
    align-items: center;

    .el-radio__label {
      display: flex;
      align-items: center;
    }
  }
}

.marketing-row {
  margin-bottom: 20px;
  width: 460px;
  margin-left: 120px;

  .marketing-row-conditions {
    display: flex;

    > .el-form-item:first-child {
      margin-right: 20px;
    }

    .el-form-item__content {
      margin-left: 0 !important;
    }
  }

  .marketing-row-tooltip {
    display: flex;
    align-items: center;
    margin-bottom: 20px;

    .el-tooltip {
      margin-right: 12px;
    }
  }
}

.marketing-btn {
  .el-radio__input {
    display: none;
  }
}
</style>
